package com.mmg.cosplay.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.mmg.cosplay.entity.dto.ChatMessageDTO;
import com.mmg.cosplay.entity.R;
import com.mmg.cosplay.entity.User;
import com.mmg.cosplay.service.ChatService;
import com.mmg.cosplay.service.IRolePresetService;
import com.mmg.cosplay.service.UserService;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Tag(name="用户相关接口")
@RequiredArgsConstructor
@RestController
@RequestMapping("/user/chat")
public class UserController {

    private final UserService userService;
    private final ChatService chatService;
    private final IRolePresetService rolePresetService;

    /**
     * 获取当前登录用户的信息
     */
    @Operation(summary = "获取当前登录用户的信息")
    @GetMapping("/info")
    public ResponseEntity<User> getUserInfo() {
        return R.success(userService.getById((Serializable) StpUtil.getLoginId()));
    }

    /**
     * 获取当前登录用户的所有会话记录id列表
     */
    @Operation(summary = "获取当前登录用户的所有会话记录")
    @GetMapping("/conversations")
    public ResponseEntity<List<String>> getUserConversations() {
        Long loginId = Long.parseLong(StpUtil.getLoginId().toString());
        return R.success(userService.getUserChatConversations(loginId));
    }

    /**
     * 根据会话id获取该会话的所有消息记录
     */
    @Operation(summary = "根据会话id获取该会话的所有消息记录")
    @GetMapping("/messages/{id}")
    public List<ChatMessageDTO> getMessagesByConversationId(@PathVariable("id") String id) {
        List<ChatMessage> messagesByConversationId = userService.getMessagesByConversationId(id);
        List<ChatMessageDTO> messageList = new ArrayList<>();

        // 过滤掉SystemMessage、包含toolExecutionRequests的AI消息和TOOL_EXECUTION_RESULT消息
        List<ChatMessage> filteredMessages = messagesByConversationId.stream()
                .filter(msg -> {
                    // 过滤掉SystemMessage
                    if (msg instanceof SystemMessage) {
                        return false;
                    }
                    // 过滤掉ToolExecutionResultMessage
                    if (msg instanceof ToolExecutionResultMessage) {
                        return false;
                    }
                    // 过滤掉包含toolExecutionRequests的AI消息
                    if (msg instanceof AiMessage) {
                        AiMessage aiMessage = (AiMessage) msg;
                        if (aiMessage.hasToolExecutionRequests()) {
                            return false;
                        }
                    }
                    return true;
                })
                .toList();

        for (ChatMessage message : filteredMessages) {
            ChatMessageDTO messageDTO = new ChatMessageDTO();
            String messageType = message.type().toString();

            // 统一消息类型名称
            if ("AI".equals(messageType)) {
                messageDTO.setType("ASSISTANT");
            } else {
                messageDTO.setType(messageType);
            }

            messageDTO.setContent(getMessageContent(message)); // 使用辅助方法获取消息内容
            messageDTO.setTimestamp(String.valueOf(System.currentTimeMillis()));
            messageList.add(messageDTO);
        }

        return messageList;
    }

    private String getMessageContent(ChatMessage message) {
        if (message instanceof SystemMessage){
            return ((SystemMessage) message).text();
        } else if (message instanceof UserMessage){
            return ((UserMessage) message).singleText();
        } else if (message instanceof AiMessage){
            return ((AiMessage) message).text();
        }else {
            return "";
        }
    }

    /**
     * 重命名会话标题
     */
    @Operation(summary = "重命名会话标题")
    @PutMapping("/conversations/{memoryId}/rename")
    public ResponseEntity<Boolean> renameConversation(
            @PathVariable("memoryId") String memoryId,
            @RequestParam("title") String newTitle) {
        Boolean result = userService.renameConversation(memoryId, newTitle);
        return R.success(result);
    }

    /**
     * 删除会话
     */
    @Operation(summary = "删除会话")
    @DeleteMapping("/conversations/{memoryId}")
    public ResponseEntity<Boolean> deleteConversation(@PathVariable("memoryId") String memoryId) {
        Boolean result = userService.deleteConversation(memoryId);
        return R.success(result);
    }

    /**
     * 置顶/取消置顶会话
     */
    @Operation(summary = "置顶/取消置顶会话")
    @PutMapping("/conversations/{memoryId}/top")
    public ResponseEntity<Boolean> toggleConversationTop(
            @PathVariable("memoryId") String memoryId,
            @RequestParam("isTop") String isTop) {
        Boolean result = userService.toggleConversationTop(memoryId, isTop);
        return R.success(result);
    }
}
